// 运行时配置
import { RunTimeLayoutConfig, history } from '@umijs/max';
import { Modal, message } from 'antd';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ name: string; webSocket: WebSocket }> {
  const url = 'ws://localhost:12345'; // 替换为你的WebSocket URL
  const webSocket = new WebSocket(url);

  return new Promise((resolve) => {
    webSocket.onopen = () => {
      console.log("WebSocket successfully: 服务器链接成功")
      resolve({ name: 'ws已连接，未登录', webSocket });
    };

    webSocket.onerror = (error) => {
      console.error('WebSocket error:', error);
      resolve({ name: '出错了', webSocket: null });
    };
  });
}

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
// export async function getInitialState(): Promise<{ name: string }> {
//   return { name: 'zzz' };
// }

/**
 * 配置 layout
 *
 * 参考链接：https://umijs.org/docs/max/layout-menu#%E8%BF%90%E8%A1%8C%E6%97%B6%E9%85%8D%E7%BD%AE
 * @returns
 */
export const layout: RunTimeLayoutConfig = (props: any) => {
  const { initialState } = props;
  const [messages, setMessages] = useState<string[]>([]);
  const [webSocket, setWebSocket] = useState<WebSocket | null>(null);

  useEffect(() => {
    if (initialState?.webSocket) {
      setWebSocket(initialState.webSocket);

      initialState.webSocket.onmessage = (event: MessageEvent<string>) => {
        const data = JSON.parse(event.data)
        console.log(data)

        switch (data.type) {
          case 'success':
            message.success(`WebSocket success: ${String(data.message)}`);
            break;

          case 'info':
            message.info(`WebSocket info: ${String(data.message)}`);
            break;

          case 'error':
            message.error(`WebSocket error: ${String(data.message)}`);
            break;

          case 'filteredCourseData':
            message.success(`已筛选到课程数据 ${data.message}`);
            localStorage.setItem('filteredCourseData', JSON.stringify(data.message.data));
            break;

          default:
            break;
        }
        setMessages((prevMessages) => [...prevMessages, event.data]);
      };

      initialState.webSocket.onclose = () => {
        console.log('WebSocket connection closed');
        setWebSocket(null);
      };

      initialState.webSocket.onerror = (error: Event) => {
        console.error('WebSocket error:', error);
        setWebSocket(null);
      };
    }
  }, [initialState]);

  const send = (data: any) => {
    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
      // webSocket 链接成功

      if (data.type === 'text') {
        webSocket.send(JSON.stringify(data));
      } else if (data.type === 'file') {
        webSocket.send(JSON.stringify({ data: data, fileName: data.fileName, types: "UpdateCourseInfo" }));
      }
    }
  }

  return (
    {
      logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
      menu: {
        locale: false,
      },
      fixSiderbar: true,
      layout: 'mix',
      splitMenus: false,
      // navTheme: 'realDark',
      contentWidth: 'Fluid',
      colorPrimary: $PRIMARY,
      siderMenuType: 'sub',
      fixedHeader: true,
      siderWidth: 188,
      // 通过token修改主题色
      token: {
        sider: {
          colorMenuBackground: '#ffffff',
        },
        header: {
          colorBgHeader: '#001529',
          colorHeaderTitle: '#ffffff',
          heightLayoutHeader: 48,
        },
        pageContainer: {},
      },
      logout: (initialState: any) => {
        console.log(initialState);
        Modal.confirm({
          title: '注销登录',
          content: '确定要注销登录吗？',
          okText: '确定',
          cancelText: '取消',
          okButtonProps: {
            danger: true,
          },
          onOk: () => {
            history.replace('/login');
          },
        });
      },
      // actionsRender: (props) => {
      //   if (props.isMobile) return [];
      //   if (typeof window === 'undefined') return [];
      //   return [
      //     <InfoCircleFilled key="InfoCircleFilled" />,
      //     <QuestionCircleFilled key="QuestionCircleFilled" />,
      //     <GithubFilled key="GithubFilled" />,
      //   ];
      // },
      webSocket: {
        messages,
        send,
      }
    }
  )
};
